# --*-- coding:UTF-8 --*--

from  lxml import etree

def test():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=etree.tostring(html)
    print(result.decode('utf-8'))

#获取所有节点
def findAll():
    html=etree.parse('./test.html',etree.HTMLParser())
    #result=html.xpath('//*')
    result=html.xpath('//li')
    print(result)

#获取子节点
def findChildren():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li/a')
    print(result)

#获取父节点
def findParent():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//a[@href="link4.html"]/../@class')
    print(result)

#获取匹配属性的节点
def findAttr():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li[@class="item-0"]')
    print(result)

#获取文本
def findText():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li[@class="item-0"]/text()')
    print(result)

#获取属性
def getAttr():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li/a/@href')
    print(result)

#属性多值匹配(获取包含多个属性值的节点)
def findContainsMoreAttrValue():
    text='''
        <li class="li li-first"><a href="link.html">first item</a></li>
    '''
    html=etree.HTML(text)
    result=html.xpath('//li[contains(@class,"li")]/a/text()')
    print(result)

#多属性匹配(获取包含多个属性的节点)
def findContainsMoreAttr():
    text='''
        <li class="li li-first" name="item"><a href="link.html">first item</a></li>
    '''
    html=etree.HTML(text)
    result=html.xpath('//li[contains(@class,"li") and @name="item"]/a/text()')
    print(result)

#按序选择
def findBySort():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li[1]/a/text()')
    print(result)
    result=html.xpath('//li[last()]/a/text()')
    print(result)
    result=html.xpath('//li[position()<3]/a/text()')
    print(result)
    result=html.xpath('//li[last()-2]/a/text()')
    print(result)

#按节点轴选择
def findByAncestor():
    html=etree.parse('./test.html',etree.HTMLParser())
    result=html.xpath('//li[1]/ancestor::*')
    print(result)
    result=html.xpath('//li[1]/ancestor::div')
    print(result)
    result=html.xpath('//li[1]/child::a[@href="link1.html"]')
    print(result)
    result=html.xpath('//li[1]/descendant::span')
    print(result)
    result=html.xpath('//li[1]/following::*[2]')
    print(result)
    result=html.xpath('//li[1]/following-sibling::*')
    print(result)

if __name__ == '__main__':
    #findAll()
    #findChildren()
    #findParent() 
    #findAttr()
    #findText()
    #getAttr()
    #findContainsMoreAttrValue()
    #findContainsMoreAttr()
    #findBySort()
    findByAncestor()

